package com.xincongjun.media.convert.image;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

import static com.xincongjun.media.utils.FileUtil.getRealFileType;
import static com.xincongjun.media.utils.ImageMagickUtil.useImageMagickConvertFileType;

public class ConvertImage {

    private static final Logger logger = LoggerFactory.getLogger(ConvertImage.class);

    public static void convertImageFile(String directoryPath, String targetFileType) {
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            logger.error("无效路径: {}", directoryPath);
            return;
        }

        File[] files = directory.listFiles();
        if (files == null || files.length == 0) {
            logger.error("路径下不存在文件: {}", directoryPath);
            return;
        }

        for (File file : files) {
            if (file.isFile()) {
                convertFilesProcessFile(file, targetFileType);
            }
        }

        logger.info("所有文件处理完成！");
    }

    private static void convertFilesProcessFile(File file, String targetFileType){
        String filePath = file.getAbsolutePath();

        try {
            String realFileType = getRealFileType(filePath);
            if (targetFileType.equals(realFileType)) {
                return;
            }else {
                logger.error("文件后缀名与 realFileType 不一致: {}", filePath);
            }

            // 使用 ImageMagick 转换文件格式
            useImageMagickConvertFileType(file, targetFileType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
